import Vue from 'vue'
import cube from 'cube-ui'
import api from '../common/config/api'
import moment from 'moment'
import qs from 'qs'
import readScore from './readScore'
import encrypt from '@/utils/encryptUtils'

Vue.use(cube)
let d = new Vue()
let loading = null
let backTime = new Date().getTime()
export default {
  readScore,
  //提示框
  tip (msg, delayTime) {
    if (!msg) {
      return false
    }
    const toast = d.$createToast({
      time: delayTime || 2000,
      txt: msg,
      type: 'txt'
    })
    toast.show()
  },
  //数据加载框
  showLoading (msg, delayTime) {
    loading = d.$createToast({
      time: delayTime || 0,
      txt: msg || '数据加载中...',
      type: 'loading'
    })
    loading.show()
  },
  //隐藏数据加载框
  hideLoading () {
    loading && loading.hide()
  },
  //弹出框
  alert (msg, fn) {
    if (!msg) {
      return false
    }
    d.$createDialog({
      type: 'alert',
      title: '温馨提示',
      content: msg,
      icon: '',
      onConfirm: () => {
        fn && fn()
      }
    }).show()
  },
  //替换换行符
  resumeEnter (str) {
    if (!str) {
      return str
    }
    return str.replace(/\n|\r/g, '<br>')
  },
  //跳转到登录页面
  login () {
    window.myvue.$store.state.lastPage = window.myvue.$route.path
    window.myvue.$router.push({'name': 'login'})
    return {}
  },
  //清除极光别名和跳转到登录页面-退出登录
  loginOut () {
    if (window.android) {
      // 删除极光推送别名
      window.android.deleteAliass()
    }
    window.myvue.$localStorage.remove('userInfo')
    let backLen = window.history.length - 2
    // window.history.go(-backLen)
    window.myvue.$router.replace({'name': 'login'})
  },
  //获取token
  getToken () {
    let token = window.myvue.$sessionStorage.get('token')
    if (!token) {
      console.log('tools no token')
      return this.login()
    }
    return token
  },
  //获取本机设备号 安卓 ios  统一获取
  getDeviceId () {//获取本机标识码 ios 安卓
    if(window.webkit !== undefined){
      window.android.getDeviceId();
      return window.myvue.$localStorage.get("deviceIdIOS") || 'unknown'
    }
    if (window.android && window.android.getDeviceId) {
      return window.android.getDeviceId()
    }
    return 'unknown'
  },
  // 获取ios设备编号
  getDeviceIdIOS () {//获取ios唯一编码
    return window.myvue.$localStorage.get("deviceIdIOS") || 'unknown'
  },
  //设置token
  setToken (token) {
    return window.myvue.$sessionStorage.set('token', token)
  },
  /**
   * 获取get参数
   */
  getQuery (url) {
    if (url.indexOf('?') >= 0) {
      return qs.parse(url.split('?')[1])
    }
    return {}
  },
  /**
   * 设置参数
   */
  setQuery (url, query) {
    url = url.split('?')[0]
    return `${url}?${qs.stringify(query)}`
  },
  /**
   * 追加参数
   */
  addQuery (url, params) {
    let defParams = this.getQuery(url)
    url = url.split('?')[0]
    return `${url}?${qs.stringify(_.extend(defParams, params))}`
  },
  //  会议状态(-1:续办,0:待开,1:开始签到,2：结束签到,3：填写会议内容,4：结束)
  getMeetStatus (status,item) {
    if (item.statusLaveb) {
      return item.statusLaveb
    }
    let oStatusText = {
      "-1": '续办',
      "0": '待开',
      "1": '开始签到',
      "2": '结束签到',
      "3": '填写会议内容',
      "4": '结束'
    }
    return oStatusText[status]
  },
  // 是否接受证件清单
  sfjszjqd (str) {
    // Y 有证件清单，N没有
    let data = {
      'Y': '是',
      'N': '否'
    }
    return data[str]
  },
  percent (a, b) {
    a = a || 0
    b = b || 0
    let ret = parseInt(a / b * 100)
    return Number.isNaN(ret) ? 0 : ret
  },
  // 转成数字
  parseNumber (str) {
    try {
      let ret = parseInt(str)
      ret = Number.isNaN(ret) ? 0 : ret
      return ret
    } catch (e) {
      return 0
    }
  },
  // 时间转换
  formateYearSecond (str) {
    if (str === undefined || str === null) {
      return ''
    }
    moment.lang('zh-cn')
    return moment(str).format('YYYY-MM-DD HH:mm')
  },
  formateMonthSecond (str) {
    if (str === undefined || str === null) {
      return ''
    }
    moment.lang('zh-cn')
    return moment(str).format('MM-DD  HH:mm')
  },
  formateZh (str) {
    if (str === undefined || str === null) {
      return ''
    }
    moment.lang('zh-cn')
    return moment(str).format('YYYY年MM月DD日')
  },
  formateMonthSecondM (str) {
    if (str === undefined || str === null) {
      return ''
    }
    moment.lang('zh-cn')
    return moment(str).format('MM月DD日,HH:mm')
  },
  formatDate (str) {
    if (str === undefined || str === null) {
      return ''
    }
    return moment(str).format('YYYY-MM-DD')
  },
  // 是当天就显示时分，如果是昨天以前就显示完整的时间
  formatHM (str) {
    if (str === undefined || str === null) {
      return ''
    }
    if (moment().dayOfYear() - moment(str).dayOfYear() > 0) {
      return moment(str).format('YYYY-MM-DD HH:mm')
    }
    return moment(str).format('HH:mm')
  },
  // 是当天就显示时分，如果是昨天以前就显示日期
  getTimeNew(createTime) {
    if (createTime === undefined || createTime === null) {
      return ''
    }
    if (moment(createTime).year() < moment().year()) {
      return moment(createTime).format("YYYY-M-D");
    } else if (moment(createTime).year() === moment().year() && moment(createTime).dayOfYear() === moment().dayOfYear()) {
      return moment(createTime).format("HH:mm:ss");
    }
    return moment(createTime).format("MM-DD");
  },
  //判断是否为图片
  isImage (fileName) {
    let arrExt = fileName.split('.')
    return 'PNG,JPG,JPEG,BMP,GIF'.split(',').indexOf(arrExt[arrExt.length - 1].toUpperCase()) > -1
  },
  //转成Json格式
  hasFile (str) {
    if (str === '' || str === undefined || str === null || str === '[]') {
      return false
    }
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  },
  // 获取用户信息
  getUserInfo () {
    return window.myvue.$localStorage.get('userInfo') || {}
  },
  // 获取appKeyId
  getAppKeyId () {
    return this.getUserInfo().appKeyId
  },
  // 统一对数据添加token
  addTokenToObject (data) {
    if (data['token']) {
      return data
    } else {
      data['token'] = this.getUserInfo().token
      return data
    }
  },
  //获取性别
  getSex (sex) {
    if (!sex) {
      return ''
    }
    if (sex === 'Male'|| sex === '男') {
      return '男'
    } else if(sex === 'Female' || sex === '女') {
      return '女'
    } else {
      return sex
    }
  },
  //首页
  goHome () {
    window.myvue.$router.replace({name: 'home'})
  },
  /*对话框数记录*/
  dialog (b = 1, dialogInstance) {
    window._dialogInstance = dialogInstance
    console.log('-------------dialog------1--------')
    if (window._dialogNum !== undefined) {
      console.log('-------------dialog------2--------')
      window._dialogNum += b
      if (b === 1) {
        console.log('-------------dialog------4--------')
        console.log()
        window._dialogInstance = dialogInstance
      }
      return true
    } else {
      console.log('-------------dialog------3--------')
      window._dialogNum = b
    }
  },
  getDialogNum () {
    return window._dialogNum || 0
  },
  dialogDestroy () {
    window._dialogInstance = undefined
  },
  //隐藏对话框
  hideDialog () {
    console.log('-------------hideDialog------1--------window._dialogInstance,', window._dialogInstance)
    if (window._dialogInstance) {
      console.log('-------------hideDialog------2--------')
      window._dialogInstance.back()
      return true
    } else {
      console.log('-------------hideDialog------3--------')
      return false
    }
  },
  //暂停播放音频
  stopAudio () {
    window.audioPlayer.pause()
  },
  //播放音频
  playAudio () {
    window.audioPlayer.show()
  },
  // 重写history.back 为跳转做控制
  back () {
    console.log('back from custom')
    if (window.onBack) return window.onBack()
    // 跳转前判断当前页面，为各个页面设置返回路径
    let nowTime = new Date().getTime()
    let currentRouteName = window.myvue.$route.name
    let home = 'home' // 首页
    let routesObject = {
      'home': 'home',
      // 'newsChannel': 'otherPlatform'
    }
    if (['videoDetail', 'longVideo'].includes(currentRouteName)) {
      window.audioPlayer.show()
    }
    if (this.getDialogNum() > 0) {
      if (this.hideDialog()) {
        return false
      }
    }
    if (home === currentRouteName) {
      return window.android.exitApp && window.android.exitApp()
      // if (nowTime - backTime < 500) {
      //   // 退出清除用户信息
      //   window.myvue.$localStorage.remove('userInfo')
      //   // 退出应用
      //   window.android.exitApp && window.android.exitApp()
      // } else {
      //   backTime = nowTime
      // }
    }
    if (nowTime - backTime < 300) {
      return false
    }
    backTime = nowTime
    if (!routesObject[currentRouteName]) {
      return history.go(-1)
    }
    window.myvue.$router.replace({'name': routesObject[currentRouteName]})
  },
  // 调起输入法，键盘自动上滑
  inputUp (target) {
    setTimeout(function () {
      target.scrollIntoViewIfNeeded()
    }, 100)
    /* ele.addEventListener('focus', function () {
      // 自动反弹 输入法高度自适应
      var winHeight = $(window).height(); // 获取当前页面高度
      $(window).resize(function() {
        var thisHeight = $(this).height();
        if (winHeight - thisHeight > 50) {
          //当软键盘弹出，在这里面操作
          $('body').css('height', winHeight + 'px');
        } else {
          //当软键盘收起，在此处操作
          $('body').css('height', '100%');
        }
      });
    }); */
  },
  //判断是否直接请求阿里的地址
  indexOfHttp(listPicUrl){
    if(listPicUrl!=null && listPicUrl && listPicUrl.indexOf("http")!=-1){
      return true
    }else{
      return false
    }
  },
  //判断是否为空字符串或空格 true 为空
  isNullStr(str) {
    if ( str == "" ) {
      return true;
    }
    var regu = "^[ ]+$";
    var re = new RegExp(regu);
    return re.test(str);
  },
  // 获取图片地址
  getImgUrl (fileId) {
    let token = this.getToken()
    return encrypt.EncryptUrl(`${api.downLoadFile}${fileId}?access_token=${token}`)
  },
  // 用户头像
  getAvatarUrl (userId) {
    let token = this.getToken()
    return encrypt.EncryptUrl(`${api.userAvatar}${userId}?access_token=${token}`)
  },
  nativeDownLoad (url, fileName) {
    this.tip('下载: ' + fileName)
    if (window.android && window.android.downloadFile) {
      url = this.addQuery(url, {token: this.getToken()}) // 追加或更新token
      url = encrypt.EncryptUrl(url)  // 加密
      window.android.downloadFile(url, fileName)
    }
  },
  //  党员的角色：NULL:无权限,FZDX:发展对象,YBDY:预备党员,ZSDY:正试党员,LLY:党建联络员,ZBFSJ:支部副书记,ZBSJ:支部书记,DWB:党务办,DW:党委
  getRoleType (status) {
    let roleTypeText = {
      0: "NULL",
      1: 'FZDX',
      2: 'YBDY',
      3: 'ZSDY',
      4: 'LLY',
      5: 'ZBFSJ',
      6: 'ZBSJ',
      7: 'DWB',
      8: 'DW'
    }
    return roleTypeText[status]
  },
  // 党务公开判断是否有编辑、删除权限
  hasRoleType (roleType) {
    if (roleType === this.getRoleType(4) || roleType === this.getRoleType(5)
    || roleType === this.getRoleType(6) || roleType === this.getRoleType(7)) {
      return true
    } else {
      return false
    }
  },
  // 党务办可以编辑和删除自己支部和其他支部
  hasDwbRoleType (roleType) {
    if (roleType === this.getRoleType(7)) {
      return true
    } else {
      return false
    }
  },
  // 是否是党务办
  isDWB () {
    return window.myvue.$localStorage.get('roleType') === 'DWB'
  },
  //清除store里面的数据
  clearStoreData (instance) {
    delete instance.$store.state[instance.$route.name + '-storeData']
  },
  //设置store里面的数据
  storeData (instance, storeKeys) {
     let storeData = {_storeTime: Date.now()}
    storeKeys.forEach(key => {
      storeData[key] = instance[key]
    })
    instance.$store.state[instance.$route.name + '-storeData'] = storeData
  },
  //获取store里面的数据
  resumeStoreData (instance) {
    let data = instance.$store.state[instance.$route.name + '-storeData']
    if (!data) {
      return false
    }
    for (let key in data) {
      instance[key] = data[key]
    }
    return data
  },
  //判断是否为空
  isNoData (oData) {
    console.log('isNoData ',oData)
    if (!oData) return true
    if (typeof oData === 'object' && Object.keys(oData).length <= 0) return true
    if (Array.isArray(oData) && oData.length <= 0) return true
    if (typeof oData === 'string') return true
    return false
  },

  //计算两个时间的时间差（d,h,m,s）time2 后者时间,time1 前者时间,type 返回类型 (d,天，h,时,m 分,s 秒)
  //JingJian 2020年12月14日 21:19:10
  formatDataUtil(time1, time2, type) {
    let oldTime = moment(moment(time1).format('YYYY-MM-DD HH:mm:ss'))
    let newTime = moment(moment(time2).format('YYYY-MM-DD HH:mm:ss'));
    if (type === 'm') {
      return newTime.diff(oldTime, 'minutes');
    } else if (type === 'h') {
      return newTime.diff(oldTime, 'hours');
    }  else if (type === 'd') {
      return newTime.diff(oldTime, 'day');
    } else {
      return newTime.diff(oldTime, 'seconds');
    }
  },
  //判断不为空 true 不为空 false 为空
  NotIsNull(object){
    return (object && object != '' && object != null && typeof object !='undefined')
  },
  //判断是不是ios设备
  isIos(){
    let u = navigator.userAgent;
    // let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    return isiOS
  },
  //根据id去重  By jingjian
  uniqueById(arr) {
     const res = new Map();
     return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
  },
  //最小数不会低于0
  getMinZero(num){
    if(Number(num)<0){
      return 0
    }
    return num
  },
/*  //去掉左边的空白
  trimLeft(s){
    if(s == null) {
      return "";
    }
    var whitespace = new String(" \t\n\r");
    var str = new String(s);
    if (whitespace.indexOf(str.charAt(0)) != -1) {
      var j=0, i = str.length;
      while (j < i && whitespace.indexOf(str.charAt(j)) != -1){
        j++;
      }
      str = str.substring(j, i);
    }
    return str;
  },
  //去掉右边的空白
  trimRight(s){
    if(s == null) return "";
    var whitespace = new String(" \t\n\r");
    var str = new String(s);
    if (whitespace.indexOf(str.charAt(str.length-1)) != -1){
      var i = str.length - 1;
      while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){
        i--;
      }
      str = str.substring(0, i+1);
    }
    return str;
  }*/
}
